package com.pb.metadata.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pb.infra.oth.entity.common.Page;
import com.pb.infra.oth.entity.common.Result;
import com.pb.infra.oth.service.SequenceGeneratorService;
import com.pb.infra.oth.util.JwtTokenConfig;
import com.pb.infra.oth.util.StringUtil;
import com.pb.infra.oth.util.UserInfo;
import com.pb.metadata.mapper.FilterTreeManMapper;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 过滤树管理
 *
 * @Author:liudebao
 * @Date: 2021/05/01
 */
@Service
public class FilterTreeManService {
    /**
     * DAO映射对象
     */

    @Autowired
    private SequenceGeneratorService sequenceGeneratorService;

    @Autowired
    private FilterTreeManMapper filterTreeManMapper;

    @Resource
    private JwtTokenConfig jwtTokenConfig;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 查询过滤树信息
     *
     * @param map
     * @return
     */
    public Result select(Map<String, Object> map, Page page, HttpServletRequest request) {
        if (page != null && page.getPageIndex() != null && page.getPageSize() != null) {
            PageHelper.startPage(page.getPageIndex(), page.getPageSize());
        }
        /*String token = request.getHeader(jwtTokenConfig.getHeader());
        UserInfo userInfo = (UserInfo)redisTemplate.opsForValue().get(token);
        if ("1".equals(userInfo.getManageFlag()) &&  !StringUtil.isEmpty(map.get("corpId")) && map.get("corpId").toString().equals(userInfo.getCorpId())) {
            map.put("manageFlag", 1);
        } else {
            map.put("manageFlag", 0);
        }*/
        List<Map<String, Object>> list = filterTreeManMapper.selAllTree(map);
        return Result.ok(new PageInfo(list).getTotal(), list);
    }

    public Result selectTree(Map<String, Object> map, HttpServletRequest request) {
        String token = request.getHeader(jwtTokenConfig.getHeader());
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        String userId = (String)claims.get("sub");
        UserInfo userInfo = (UserInfo)redisTemplate.opsForValue().get(token);

        List<Map<String, Object>> list = filterTreeManMapper.selNodeList(map);
        List<Map<String, Object>> list1 = new ArrayList<>();
        if (!StringUtil.isEmpty(map.get("sourceId"))) {
            list1 = filterTreeManMapper.selMetaDataTree(map);

        }
        List<String> list2 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            list2.add(list.get(i).get("rollupNode").toString());
        }

        Map<String, Object> map1 = new HashMap<>();
        map1.put("checked", list2);
        map1.put("treeList", list1);
        return Result.ok(map1);
    }

    public Result selectMetaTree(Map<String, Object> param) {
        //maIdListMapper.selectByExample(null)
        return Result.ok(filterTreeManMapper.select(param));
    }

    /**
     * 保存参数应用信息
     *
     * @param paramMap 请求参数
     * @param request 请求
     * @return Map<String, Object> 操作返回结果
     */
     @Transactional
    public void insertFilterTree(Map<String, Object> paramMap, HttpServletRequest request) {
        //FilterTree filterTree = new FilterTree();
        String seqId = sequenceGeneratorService.getNextIdStr("FILTER", "FILTER");
        paramMap.put("filterId", seqId);
        String token = request.getHeader(jwtTokenConfig.getHeader());
        UserInfo userInfo = (UserInfo)redisTemplate.opsForValue().get(token);
         paramMap.put("corpId", userInfo.getCorpId());
        /*filterTree.setTreeId(seqId);
        filterTree.setTreeName(paramMap.get("treeName").toString());
        filterTree.setSourceId(paramMap.get("sourceId").toString());
        filterTreeMapper.insertSelective(filterTree);*/
        filterTreeManMapper.insertData(paramMap);
    }

    public List<String> getNodeList(List<String> arrList, List<Map<String, Object>> list2) {
        for (int i = 0; i < list2.size(); i++) {
            arrList.add(list2.get(i).get("id").toString());
            if (!StringUtil.isEmpty(list2.get(i).get("children"))) {
                List<Map<String, Object>> list3 = (List<Map<String, Object>>)list2.get(i).get("children");
                arrList = getNodeList(arrList, list3);
            }
        }
        return arrList;
    }

    /**
     * 修改参数应用信息
     *
     * @param paramMap 请求参数
     * @return Map<String, Object> 操作返回结果
     */
     @Transactional
    public void update(Map<String, Object> paramMap) {
        //idtViewFilterMapper.deleteByPrimaryKey(paramMap.get("treeId").toString());
        filterTreeManMapper.delNode(paramMap.get("treeId").toString());
        List<Map<String, Object>> list = (List<Map<String, Object>>)paramMap.get("treeList");
        List<Map<String, Object>> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            /*if (!StringUtil.isEmpty(list.get(i).get("leafFlag")) && "1".equals(list.get(i).get("leafFlag").toString())) {
            }*/
            /*IdtViewFilter idtViewFilter = new IdtViewFilter();
            idtViewFilter.setSysIdNum(paramMap.get("treeId").toString());
            idtViewFilter.setRollupSysId(list.get(i).get("sourceId").toString());
            idtViewFilter.setRollupLevel(Integer.parseInt(list.get(i).get("lvl").toString()));
            idtViewFilter.setRollupNode(list.get(i).get("id").toString());
            idtViewFilterMapper.insertSelective(idtViewFilter);*/
            Map<String, Object> map1 = new HashMap<>();
            if (!StringUtil.isEmpty(map1.get("children"))) {
                list1.add(map1);
            }
        }
        List<String> delList = new ArrayList<>();
        for (int i = 0; i < list1.size(); i++) {
            Map<String, Object> map2 = list1.get(i);
            List<String> arrayList = new ArrayList<>();
            List<Map<String, Object>> list2 = (List<Map<String, Object>>)map2.get("children");
            arrayList = getNodeList(arrayList, list2);
            boolean flag = false;
            for (int j = 0; j < arrayList.size(); j++) {
                for (int k = 0; k < list.size(); k++) {
                    if (list.get(k).get("id").toString().equals(arrayList.get(j))) {
                        delList.add(list1.get(i).get("id").toString());
                        flag = true;
                        break;
                    }
                }
                if (flag) {
                    break;
                }
            }
        }
        for (int i = 0; i < delList.size(); i++) {
            int index = -1;
            for (int j = 0; j < list.size(); j++) {
                if (list.get(j).get("id").toString().equals(delList.get(i))) {
                    index = j;
                    break;
                }
            }
            if (index != -1) {
                list.remove(index);
            }
        }
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("treeId", paramMap.get("treeId").toString());
            map.put("sourceId", list.get(i).get("sourceId").toString());
            map.put("lvl", list.get(i).get("lvl").toString());
            map.put("nodeId", list.get(i).get("id").toString());
            filterTreeManMapper.insertNodeList(map);
        }
    }

     @Transactional
    public void updateName(Map<String, Object> paramMap) {
        /*FilterTree filterTree = new FilterTree();
        filterTree.setTreeId(paramMap.get("treeId").toString());
        filterTree.setTreeName(paramMap.get("treeName").toString());
        filterTreeMapper.updateByPrimaryKeySelective(filterTree);*/
        filterTreeManMapper.updateData(paramMap);
    }

    /**
     * 删除参数应用信息
     *
     * @param map 请求参数
     * @return Map<String, Object> 操作返回结果
     */
     @Transactional
    public void delete(List<String> map) {
        // 删除参数
        for (String treeId : map) {
           /* filterTreeMapper.deleteByPrimaryKey(treeId);
            idtViewFilterMapper.deleteByPrimaryKey(treeId);*/
            filterTreeManMapper.delData(treeId);
            filterTreeManMapper.delNode(treeId);
        }
    }

    /**
     * 根据法人查询维度信息
     * @param param 参数信息
     * @return Result
     */
    public Result selDimType(Map<String, Object> param) {
        return Result.ok(filterTreeManMapper.selDimType(param));
    }

    /*public Result selRuleFilter(Map<String, Object> paramMap) {
        return Result.ok(filterTreeManMapper.selRuleFilter(paramMap));
    }*/
}
